package com.gitee.threefish.idea.json;

/**
 * @author Nekio
 */
import com.gitee.threefish.idea.json.components.TreeParent;
import org.json.JSONException;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class JsonUI extends JFrame {
    private Container container;
    private JPanel pnlNorth;
    private JPanel pnlCenter;
    private JButton showTextArea;
    private JSONObject json;

    public JsonUI() {
        activate();
    }

    private void activate() {
        this.setLayout(new BorderLayout());
        this.setSize(new Dimension(720, 640));
        this.setLocationRelativeTo(null);
        addComponents();
        addListeners();
    }

    private void addComponents() {
        container = this.getContentPane();
        activatePanels();
    }


    private void activatePanels() {
        activatePanel(activateNorthPanel(), BorderLayout.NORTH);
        activatePanel(activateCenterPanel(), BorderLayout.CENTER);
    }

    private void activatePanel(JPanel panel, String location) {
        container.add(panel, location);
    }

    private void deactivatePanel(JPanel panel) {
        if (panel != null) {
            panel.setVisible(false);
        }
    }

    private JPanel activateNorthPanel() {
        pnlNorth = new JPanel(new BorderLayout());
        showTextArea = new JButton("格式化");
        pnlNorth.add(showTextArea, BorderLayout.EAST);
        return pnlNorth;
    }

    private JPanel activateCenterPanel() {
        pnlCenter = new TreeParent(json);
        return pnlCenter;
    }

    private void addListeners() {
        showTextArea.addActionListener(evt -> {
            String json = JOptionPane.showInputDialog("输入json");
            formatJson(json);
        });
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent evt) {
                exit();
            }
        });
    }

    private void formatJson(String text) {
        try {
            json = new JSONObject(text);
            deactivatePanel(pnlCenter);
            activatePanel(activateCenterPanel(), BorderLayout.CENTER);
        } catch (JSONException je) {
            showMessage("JSON Error:\n" + je.getMessage());
        } catch (Exception e) {
            showMessage(e.getMessage());
        }
    }

    public void showMessage(String text) {
        JOptionPane.showMessageDialog(null, text, "错误", JOptionPane.WARNING_MESSAGE);
    }

    private void exit() {
        this.setVisible(false);
        this.dispose();
    }
}
